package common.store.web.dao;

import common.store.common.util.C3p0Pool;
import common.store.web.bean.Cart;
import common.store.web.bean.CartAndProduct;
import common.store.web.bean.Order;
import common.store.web.bean.orderAndProduct;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

public class OrderDao {
    private static QueryRunner qr;

    static {
        qr = new QueryRunner(C3p0Pool.getDataSource());
    }

    public static Integer addOrder(String uid) {

        String sql = "select * from t_cart where uid=?";
        try {
            List<Cart>cartList =qr.query(sql , new BeanListHandler<>(Cart.class) , uid);
            for (Cart cart : cartList) {
                String sq2 = "delete from orders where oid = ?";
                qr.update(sq2 , cart.getId());
                 String sql1 = "insert into orders(oid , pid , count ,uid) values(? , ? , ?, ?)";
                 qr.update(sql1 , cart.getId(), cart.getPid() , cart.getCount() ,cart.getUid());
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 1;

    }


    public List<orderAndProduct> getOrderList(String uid) {
        String sql = "select c.count , c.oid , p.pid  ,p.pimage, p.pname , p.shop_price shopPrice from orders c , product p where c.pid = p.pid and c.uid = ?";
        try {
            return qr.query(sql , new BeanListHandler<>(orderAndProduct.class) , uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Collections.EMPTY_LIST;
    }

    public void deleteALLOrderById(String uid) {
        String sql = "delete from orders where uid = ?";
        try {
            qr.update(sql , uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Integer update(Order order) {
        String sql = "update orders set name = ? , address=? , phone=? where uid = ?";

        try {
            return qr.update(sql , order.getName() ,order.getAddress(), order.getPhone(),order.getUid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
